package com.tql.kingdee.event;

import cn.hutool.extra.spring.SpringUtil;
import com.ruoyi.common.core.utils.CalculatedValueUtil;
import com.ruoyi.common.core.utils.SpringUtils;
import com.tql.kingdee.bean.TqlStapPriceBean;
import com.tql.kingdee.service.StapPriceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.actuate.beans.BeansEndpoint;
import org.springframework.util.CollectionUtils;

import javax.swing.plaf.basic.BasicIconFactory;
import java.math.BigDecimal;
import java.util.List;

public class StapPriceHandlerTriggerEvent extends ActEvent<List<TqlStapPriceBean>>{
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    public StapPriceHandlerTriggerEvent(List<TqlStapPriceBean> thisList) {

        super(thisList);
        logger.info("执行触发事件--计算物料移动平均价--StapPriceHandlerTriggerEvent");
        StapPriceService stapPriceService= SpringUtil.getBean(StapPriceService.class);
        //上次的值
        List<TqlStapPriceBean> lastList=stapPriceService.findStapPrice(thisList);
        //把
        if(!CollectionUtils.isEmpty(lastList))
        for(TqlStapPriceBean thisEach:thisList)
        {
            String thiskey=thisEach.getStapCode()+thisEach.getDeptCode();
            for(TqlStapPriceBean oldEach:lastList)
            {
                String oldKey=oldEach.getStapCode()+oldEach.getDeptCode();
                if(thiskey.equals(oldKey))
                {
                    thisEach.setOldPrice(oldEach.getLastPrice());
                    thisEach.setOldNum(oldEach.getLastNum());
                }

            }
        }
        //
        thisList.stream().map(e->{
            BigDecimal lastNum=null==e.getLastNum()?BigDecimal.ZERO:e.getLastNum();
            BigDecimal lastPrice=null==e.getLastPrice()?BigDecimal.ZERO:e.getLastPrice();
            BigDecimal oldNum=null==e.getOldNum()?BigDecimal.ZERO:e.getOldNum();
            BigDecimal oldPrice=null==e.getOldPrice()?BigDecimal.ZERO:e.getOldPrice();
           BigDecimal thisAmount= CalculatedValueUtil.multiplyB(lastNum,lastPrice);
           BigDecimal oldAmount=CalculatedValueUtil.multiplyB(oldNum,oldPrice);
           BigDecimal sumAmount=CalculatedValueUtil.additionDecimal(thisAmount,oldAmount);
            BigDecimal sumNum=CalculatedValueUtil.additionDecimal(lastNum,oldNum);
            BigDecimal newWeightedPrice=CalculatedValueUtil.division(sumAmount,sumNum);
            e.setWeightedPrice(newWeightedPrice);
        return e;
        });

        stapPriceService.mergeStapPriceByStapCodeAndDeptCode(thisList);

    }
}
